<script setup lang="ts">
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
// 引入用户相关的小仓库
import useUserStore from "@/store/modules/user.ts";
import { useRouter, useRoute } from "vue-router";
import { ElNotification } from "element-plus";
import { getTimeRange } from "@/utils/time";

let $router = useRouter();
let $route = useRoute();

// 收集登录数据
let loginForm = reactive({
  username: "admin",
  password: "atguigu123",
});

// 获取表单的dom对象
let loginForms = ref();

let loading = ref(false);

// 获取用户相关的小仓库
let userStore = useUserStore();

const login = async () => {
  // 方法执行，接受一个回调函数或者返回一个promise
  await loginForms.value.validate();
  loading.value = true;
  try {
    await userStore.userLogin(loginForm);
    let redirect: string = ($route.query.redirect as string) || "/";
    $router.push(redirect);
    ElNotification.success({
      title: "欢迎回来",
      message: `Hi,${getTimeRange(new Date())}好！`,
    });
  } catch (e: any) {
    ElNotification.error({
      title: "登录失败",
      message: e.message,
    });
  }
  loading.value = false;
};

// 自定义校验规则：用户名
// 参数一：规则本身 rule 规则校验对象
// 参数二：当前输入框的值 value
// 参数三：回调函数 callback 放行函数
const checkUsername = (rule: any, value: any, callback: any) => {
  // console.log("规则本身：", rule);
  if (!value) {
    return callback(new Error("请输入用户名"));
  }
  //  校验用户名的正则表达式 3-10位
  const regUserName = /^[a-zA-Z0-9_-]{3,10}$/;
  if (!regUserName.test(value)) {
    return callback(new Error("长度在 3 到 10 个字符"));
  }
  callback();
};

const checkPassword = (rule: any, value: any, callback: any) => {
  // console.log("规则本身：", rule);
  if (!value) {
    return callback(new Error("请输入密码"));
  }
  //  校验密码的正则表达式 6-20位
  const regPassword = /^[a-zA-Z0-9_-]{6,20}$/;
  if (!regPassword.test(value)) {
    return callback(new Error("长度在 6 到 20 个字符"));
  }
  callback();
};

// 定义表单验证规则
// 一个属性就是对一种属性的校验
// 一个属性可以有多个校验规则，所以是一个数组
const rules = {
  // username: [
  //   //   每一种校验规则都必须有一个触发方式trigger
  //   //   常见触发方式：blur 失去焦点时触发、change 值改变时触发
  //   { required: true, message: "请输入用户名", trigger: "blur" },
  //   {
  //     min: 3,
  //     max: 10,
  //     message: "长度在 3 到 10 个字符",
  //     trigger: "blur",
  //   },
  // ],
  // password: [
  //   { required: true, message: "请输入密码", trigger: "blur" },
  //   {
  //     min: 6,
  //     max: 20,
  //     message: "长度在 6 到 20 个字符",
  //     trigger: "change",
  //   },
  // ],
  username: [
    {
      validator: checkUsername,
      trigger: "blur",
    },
  ],
  password: [
    {
      validator: checkPassword,
      trigger: "blur",
    },
  ],
};

// 定义组件名称
defineOptions({
  name: "Login",
});
</script>

<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <h1>Hello</h1>
          <h2>欢迎来到登录页面</h2>
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              type="text"
              v-model="loginForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              type="password"
              v-model="loginForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              class="login_btn"
              type="primary"
              @click="login"
              >登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/background.jpg") no-repeat center center;
  background-size: cover;

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url("@/assets/images/login_form.png") no-repeat center center;
    background-size: cover;
    padding: 10%;
    border-radius: 5%; /* 整个元素圆角 */
    h1 {
      font-size: 40px;
      color: white;
      padding: 20px 0;
    }

    h2 {
      font-size: 20px;
      color: white;
      padding-bottom: 20px;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
